function reward = GetReward(P,S, mode) % returns the immediate reward for the given state

global num_players_r;
global num_players_b;

distances = zeros(1,num_players_b);
reward = 0;

B = S{1};
B_X=B{1}(1);
B_Y=B{1}(2);

absolute_x = B_X-60;

%reward = reward + ceil(absolute_x/12); % distance of the ball from opponents goal
reward = reward + (absolute_x)/6; %this component of the reward varies between 0 and -20

% check if learning agents have the posession
% if(TeamInPossession(P,S,mode))
%     reward = reward + 0;
% else
% 
% if(OpponentInPossession(P,S,mode))
%     reward = reward - 2;
% elseif(~TeamInPossession(P,S,mode)) 
%     reward = reward - 1;
% end

% relative distance from each opponent to the ball
for k = 2:numel(S),
    if(S{k}{2} == P{2}), continue; end %only check opposing players
    Pk = S{k};
    Pk_X=Pk{1}(1);
    Pk_Y=Pk{1}(2);
    
    Pk_R=sqrt((B_Y-Pk_Y)^2+(B_X-Pk_X)^2);  % relative distance to the ball
    
    if (Pk_R < 20)
        reward = reward + (Pk_R-20)/10;
    end
    %distances(k-(1+num_players_r)) = Pk_R;
end

% min_distance = min(distances);
% if(min_distance < 20) 
%     reward = reward + (min_distance-20)/10;
% else
%     reward = reward + 0;
% end

%reward = reward/10;

end